using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;



namespace FanDongping.Stock
{
    public class TradeHistory
    {
        private static string tradeHistoryPath = AppDomain.CurrentDomain.BaseDirectory + "TradeHistory.xml";
        private List<Trade> trades = new List<Trade>();

        [XmlIgnore]
        public bool Modified
        {
            get
            {
                bool b = false;
                foreach (Trade t in trades)
                {
                    b |= t.Modified;
                }
                return b;
            }
            set
            {
                foreach (Trade t in trades)
                {
                    t.Modified = value;
                }
            }
        }

        public Trade[] Trades
        {
            get
            {
                return trades.ToArray();
            }
            set
            {
                trades.Clear();
                trades.AddRange(value);
            }
        }

        public void Add(Trade trade)
        {
            trades.Add(trade);
        }


        #region  functions

        public bool Save()
        {
            XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(TradeHistory));

            FileInfo fi = new FileInfo(tradeHistoryPath);
            if (fi.Exists)
            {
                fi.IsReadOnly = false;
            }

            FileStream fa = fi.OpenWrite();
            fa.SetLength(0);
            XmlTextWriter wtr = new XmlTextWriter(fa, null);

            wtr.Formatting = Formatting.Indented;
            wtr.Indentation = 4;
            wtr.IndentChar = (char)32;

            ser.Serialize(wtr, this);
            wtr.Close();

            this.Modified = false;
            return true;

        }

        public static TradeHistory Load()
        {
            TradeHistory t;
            try
            {
                XmlSerializer r = new System.Xml.Serialization.XmlSerializer(typeof(TradeHistory));
                XmlTextReader xr = new XmlTextReader(tradeHistoryPath);
                t = (TradeHistory)r.Deserialize(xr);
                xr.Close();
            }
            catch (Exception e)
            {
                t = new TradeHistory();
            }

            t.Modified = false;
            return t;
        }

        #endregion // functions
    }
}
